var fs = require('fs'),
async = require('async');

function getSpeechLink(res, key, cb) {
    var basename = res.user.id + '/' + key + '.3gp';
    var file = __dirname + '/audio/' + basename;
    fs.exists(file, function(exists) {
        var url = null;
        if (exists) {
            url = 'http://10.0.0.7:3000/' + basename;
        } else {
            if (Math.random() > 0.5) {
                url = 'http://mp3.9ku.com/mp3/305/304935.mp3';
            }    
        }
        cb(null, url);
    });
}

function addSpeechLinks(request, episodes) {
    return async.apply(
        async.map,
        episodes,
        function (ep, cb) {
            getSpeechLink(request, ep.key, function(err, speechlink) {
                if (err) {
                    cb(err);
                    return;
                }

                if (speechlink) {
                    ep['speechlink'] = speechlink;
                } 
                cb(null, ep);
            });
        }
    );
}

function responseError(res, status, err) {
  console.log(err);
  res.writeHead(status, { 'Connection': 'close' });
  res.end(err.stack);
}

function responseSuccess(res) {
  res.writeHead(200, { 'Connection': 'close' });
  res.end('Successed!');
}

module.exports = {
    getSpeechLink: getSpeechLink,
    responseError: responseError,
    responseSuccess: responseSuccess,
    addSpeechLinks: addSpeechLinks
}
